<template>
  <div class="system-function">
    <div class="ppttit_sty">{{ $t('equipmentList') }}</div>
    <div class="search_box">
      <div class="label_sty">{{ $t('equipmentSelection') }}</div>
      <el-cascader
        ref="myCascader"
        :options="reactiveData.equipmentCategory"
        filterable
        clearable
        :placeholder="$t('selectCategory')"
        :show-all-levels="false"
        style="width: 100%"
        @change="handleCategoryChange"
      ></el-cascader>
    </div>
    <div class="search_box">
      <div class="label_sty">{{ $t('brandSelection') }}</div>
      <el-select
        v-model="reactiveData.brandIds"
        :placeholder="$t('selectBrand')"
        clearable
        multiple
        @change="handleBrandChange"
      >
        <el-option v-for="item in reactiveData.brandOptions" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
    </div>
    <div class="infinite-list-wrapper">
      <ul class="list" :style="scrollHeight">
        <li
          v-for="(item, index) in reactiveData.equipmentList"
          :key="index"
          class="list-item"
          @click="showEquipmentListDialog(item)"
        >
          <div class="img_sty">
            <img :src="item.image" :alt="item.name" />
          </div>
          <div class="msg_sty">
            <div>
              <span class="brand_sty">{{ item.brandName }}</span>
              <span class="name">{{ item.name }}</span>
            </div>
            <div>{{ $t('model') }}：{{ item.modelName }}</div>
          </div>
        </li>
      </ul>
      <p v-if="reactiveData.loading">{{ $t('loading') }}</p>
      <!-- <p v-if="noMore">{{ $t('noMore') }}</p> -->
    </div>

    <Modal
      :visible="reactiveData.dialogForSystemFunction"
      :width="680"
      closeButton
      closeOnEsc
      @closed="closeEquipmentListDialog"
    >
      <EquipmentListDialog
        :data="reactiveData.selectedEquipmentList"
        @confirm="handleConfirm"
        @cancel="closeEquipmentListDialog"
      />
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, computed } from 'vue'
import fetch from '@/api/fetch'
import Modal from '@/components/Modal.vue'
import { ElCascader, ElSelect, ElOption } from 'element-plus'
import { getDfsCustomObject } from '@/utils/process'
import EquipmentListDialog from './EquipmentListDialog.vue'
import useSystemFunction from '@/hooks/useSystemFunction'
import { getEquipFixedKey } from '@/mocks/customElement/equip'
const reactiveData = reactive<any>({
  dialogForSystemFunction: false,
  equipmentList: [],
  equipmentCategory: [],
  selectedEquipmentList: [],
  brandOptions: [],
  brandIds: [],
  Category: '',
  pageNum: 1,
  total: 0,
  loading: false,
})

const { createEquipmentSlide } = useSystemFunction()
// 查看详情
const showEquipmentListDialog = async (item: any) => {
  const { data } = (await fetch.get(`/system/eqpt/${item.id}`)) as any
  reactiveData.selectedEquipmentList = Object.assign({}, data)
  reactiveData.dialogForSystemFunction = true
}
const closeEquipmentListDialog = () => {
  reactiveData.dialogForSystemFunction = false
}

const scrollHeight = computed(() => {
  return 'height:' + ((window.innerHeight || document.documentElement.clientHeight) - 320) + 'px'
})

// 获取设备数据
const getData = async () => {
  reactiveData.loading = true
  try {
    const { rows, total } = (await fetch.get(
      `/system/eqpt/list?pageNum=${reactiveData.pageNum}&pageSize=999&brandIds=${reactiveData.brandIds}&${reactiveData.Category}`
    )) as any
    reactiveData.equipmentList = rows
    reactiveData.total = total
  }
  finally {
    reactiveData.loading = false
  }
}
// 设备分类
const handleCategoryChange = (ids) => {
  if (!ids) {
    reactiveData.Category = ''
    reactiveData.pageNum = 1
    getData()
    return
  }
  const res = getDfsCustomObject(reactiveData.equipmentCategory, ids[ids.length - 1])
  const queryString = new URLSearchParams(res).toString()
  reactiveData.Category = queryString
  getData()
}
// 品牌选择
const handleBrandChange = (id) => {
  if (!id) {
    reactiveData.pageNum = 1
    getData()
    return
  }
  getData()
}

// const noMore = computed(() => {
//   return Number(reactiveData.total) <= Number(reactiveData.pageNum) * 10
// })

// const handleNodeClick = async (item: any) => {
//   // 点击不是最下级就不触发
//   // if (item.children && item.children.length) return
//   activeItem.value = item.id;
//   const res = getDfsCustomObject(reactiveData.equipmentCategory, item.id);
//   const queryString = new URLSearchParams(res).toString();
//   // 获取设备列表
//   const { rows } = (await fetch.get(
//     "/system/eqpt/list?total=0&pageNum=1&pageSize=99&" + queryString
//   )) as any;
//   reactiveData.equipmentList = rows;
// };

interface CheckField {
  label: string;
  key: string;
  value: string;
  check: boolean;
}

interface ItemData {
  checkFields: CheckField[];
  selectFunc: any[];
}

const handleConfirm = (item: ItemData) => {
  const { checkFields } = item
  const resultMap = new Map()

  // 确保如果未勾选默认数据，不显示
  resultMap.set(getEquipFixedKey('设备名称'), '')
  resultMap.set(getEquipFixedKey('设备介绍'), '')

  checkFields.forEach((item) => {
    resultMap.set(item.key, item.value || '')
  })

  const fixedKeyArr = checkFields.map((item) => item.key.includes('field') && item.key).filter(Boolean)
  createEquipmentSlide(resultMap, fixedKeyArr)
  return closeEquipmentListDialog()
}

onMounted(async () => {
  // 获取设备分类
  const { rows } = (await fetch.get(
    '/system/category/list?pageNum=1&pageSize=9999&type=0&orderByColumn=createTime&isAsc=desc'
  )) as any
  const loopGetCategory = (data) => {
    return data.map((item) => {
      return {
        ...item,
        value: item.id,
        label: item.name,
        children: item.children?.length ? loopGetCategory(item.children) : null,
      }
    })
  }
  reactiveData.equipmentCategory = loopGetCategory(rows)
  // 获取品牌
  const data = (await fetch.get(
    '/system/brand/list?pageNum=1&pageSize=9999&type=0&orderByColumn=createTime&isAsc=desc'
  )) as any
  reactiveData.brandOptions = data.rows
  getData()
})
</script>

<style lang="scss" scoped>
.system-function {
  padding: 0 10px;
  .ppttit_sty {
    font-weight: bold;
    font-size: 14px;
    color: #333333;
    text-align: center;
    padding: 16px 0 12px;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 20px;
  }
  .search_box {
    margin-bottom: 20px;
    font-size: 14px;
    .label_sty {
      color: #999;
      margin-bottom: 18px;
    }
  }
  .infinite-list-wrapper {
    .list {
      overflow-y: scroll;
      .list-item {
        display: flex;
        margin-bottom: 10px;
        height: 80px;
        .img_sty {
          width: 80px;
          height: 80px;
          margin-right: 10px;
          border: 1px solid #eee;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            width: 80px;
            height: inherit;
            border-radius: 8px;
          }
        }
        .msg_sty {
          font-size: 12px;
          color: #999;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding: 2px 0;
          .brand_sty {
            color: #ff8800;
            background-color: #fff5ea;
            border: 1px solid #ff8d0b;
            border-radius: 2px;
            display: inline-block;
            margin-right: 4px;
            padding: 0 2px;
          }
          .name {
            font-size: 14px;
            font-weight: bold;
            color: #333;
          }
        }
      }
    }
  }
  //   display: flex;
  //   .toolbar {
  //     max-width: 100px;
  //     flex: 1.4;
  //     .box {
  //       padding: 6px 0;
  //       p {
  //         border: 1px solid #000;
  //         padding: 6px;
  //         text-align: center;
  //       }
  //     }
  //   }
  .container {
    width: 0;
    flex: 3;
    padding: 12px;
    padding-right: 0;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
    figure {
      cursor: pointer;
      width: 100px;
    }
  }
}
// .overflow {
//   overflow: hidden;
//   text-overflow: ellipsis;
//   white-space: nowrap;
// }

// .active {
//   background-color: #d8d8d8 !important;
//   transition: background-color 0.3s;
// }
// .ellipsis-multiline {
//   display: -webkit-box;
//   -webkit-box-orient: vertical;
//   -webkit-line-clamp: 2; /* 定义文本的行数 */
//   overflow: hidden;
//   text-overflow: ellipsis;
//   word-break: break-all; /* 确保纯数字文本也能正确换行 */
//   overflow-wrap: break-word; /* 确保长单词或数字能够正确换行 */
// }

// ::v-deep {
//   .el-tree-node__content {
//     overflow: hidden;
//     text-overflow: ellipsis;
//     white-space: nowrap;
//     display: block;
//   }
// }
</style>
